﻿
CKEDITOR.dialog.add('managedlink', function (editor) {
    var plugin = CKEDITOR.plugins.managedlink;

    var parseLink = function (editor, element) {
        var retval = {};

        if (element) {
            retval.pageID = element.getAttribute('pageid');

            retval.target = {};
            var target = element.getAttribute('target');
            if (target) {
                retval.target.type = target;
            }
        }

        this._.selectedElement = element;
        return retval;
    }

    return {
        title: 'Managed Link',
        minWidth: 350,
        minHeight: 230,
        contents:
        [
            {
                id: 'info',
                label: 'Link Info',
                title: 'Link Info',
                elements:
				[
					{
					    id: 'pageID',
					    type: 'select',
					    label: 'Linked Page',
					    'default': 'url',
					    items: pageLinkKeys,
					    setup: function (data) {
					        if (data.pageID) {
					            this.setValue(data.pageID);
					        }
					    },
					    commit: function (data) {
					        data.pageID = this.getValue();
					        for (var i = 0; i < pageLinkKeys.length; i++) {
					            if (pageLinkKeys[i][1] == data.pageID) {
					                data.text = pageLinkKeys[i][0];
					                break;
					            }
					        }
					    }
					}
                ]
            },
            {
                id: 'target',
                label: 'Target',
                title: 'Target',
                elements:
				[
					{
					    type: 'hbox',
					    widths: ['50%', '50%'],
					    children:
						[
							{
							    type: 'select',
							    id: 'linkTargetType',
							    label: 'Target',
							    'default': 'notSet',
							    'items':
								[
									['<not set>', 'notSet'],
									['New Window (_blank)', '_blank'],
									['Topmost Window (_top)', '_top'],
									['Same Window (_self)', '_self'],
									['Parent Window (_parent)', '_parent']
								],
							    setup: function (data) {
							        if (data.target)
							            this.setValue(data.target.type || 'notSet');
							        targetChanged.call(this);
							    },
							    commit: function (data) {
							        if (!data.target)
							            data.target = {};

							        data.target.type = this.getValue();
							    }
							}
                        ]
					}
                ]
            }
        ],

        onShow: function () {
            var editor = this.getParentEditor(),
				selection = editor.getSelection(),
				element = null;

            // Fill in all the relevant fields if there's already one link selected.
            if ((element = CKEDITOR.plugins.link.getSelectedLink(editor)) && element.hasAttribute('href'))
                selection.selectElement(element);
            else
                element = null;

            this.setupContent(parseLink.apply(this, [editor, element]));
        },

        onOk: function () {
            var attributes = {},
				removeAttributes = [],
				data = {},
				editor = this.getParentEditor();

            this.commitContent(data);

            attributes['pageid'] = data.pageID;
            attributes['href'] = 'javascript:void(0);';

            if (data.target) {
                if (data.target.type != 'notSet') {
                    attributes.target = data.target.type;
                }
                else {
                    removeAttributes.push('target');
                }
            }

            if (!this._.selectedElement) {
                // Create element if current selection is collapsed.
                var selection = editor.getSelection(),
					ranges = selection.getRanges(true);
                if (ranges.length == 1 && ranges[0].collapsed) {
                    var text = new CKEDITOR.dom.text(data.text ? data.text : attributes['pageid'], editor.document);
                    ranges[0].insertNode(text);
                    ranges[0].selectNodeContents(text);
                    selection.selectRanges(ranges);
                }

                // Apply style.
                var style = new CKEDITOR.style({ element: 'a', attributes: attributes });
                style.type = CKEDITOR.STYLE_INLINE; 	// need to override... dunno why.
                style.apply(editor.document);
            }
            else {
                // We're only editing an existing link, so just overwrite the attributes.
                var element = this._.selectedElement;

                element.setAttributes(attributes);
                element.removeAttributes(removeAttributes);

                delete this._.selectedElement;
            }
        }
    }
});